-module(cdr_saver).
-include("tr_config.hrl").

-behaviour(gen_server).
-define(SERVER,?MODULE).
-export([start/0,start_link/0,start_link/1,init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3]).
-export([do/1]).
do({cdr,Json}) ->
	gen_server:call(?SERVER,{cdr,Json});
do(save) ->
	gen_server:call(?SERVER,save);
do(json) ->
	gen_server:call(?SERVER,dump_json).
start() ->
	gen_server:start({local, ?SERVER}, ?MODULE, [#cdr_saver_cfg{}], []).
start_link(Cfg) ->
	gen_server:start_link({local, ?SERVER}, ?MODULE, [Cfg], []).
start_link() ->
	gen_server:start_link({local, ?SERVER},?MODULE, [#cdr_saver_cfg{}], []).
init([Cfg]) ->
	io:format("~p server start up~n",[?SERVER]),
  {{Year,Month,Day},{Hour,Min,Sec}} = calendar:local_time(),
  {ok,File} = file:open(io_lib:format("cdr_~B-~B-~B+~B+~B+~B.txt",[Year,Month,Day,Hour,Min,Sec]),[write]),
	{ok,{0,Cfg,[],File}}.

handle_call({cdr,Json},_,{Counter,Cfg,Json_Array,File}) when Cfg#cdr_saver_cfg.max_buffer_len =:= Counter->
	dump(file,Json_Array,File),
	{reply,ok,{1,Cfg,[Json,<<"\n">>],File}};

handle_call({cdr,""},_,{Counter,Cfg,Json_Array,File}) ->
	{reply,ok,{Counter,Cfg,Json_Array,File}};

handle_call({cdr,Json},_,{Counter,Cfg,Json_Array,File}) ->
	{reply,ok,{Counter + 1,Cfg,Json_Array ++ [Json,<<"\n">>],File}};

handle_call(save,_,{_Counter,Cfg,Json_Array,File}) ->
	dump(file,Json_Array,File),
  file:close(File),
  {{Year,Month,Day},{Hour,Min,Sec}} = calendar:local_time(),
  {ok,NewFile} = file:open(io_lib:format("cdr_~B-~B-~B+~B+~B+~B.txt",[Year,Month,Day,Hour,Min,Sec]),[write]),
	{reply,ok,{0,Cfg,[],NewFile}};
handle_call(dump_json,_,{Counter,Cfg,Json_Array,File}) ->
	{reply,
	dump(json,{Counter,Json_Array})
	,{Counter,Cfg,Json_Array,File}};
handle_call(_,_,State) ->
	{reply, "undefined fun", State}.
handle_cast(_, State) ->
	{noreply,State}.
handle_info(_, State) ->
	{noreply,State}.
terminate(_, _) ->
	ok.
code_change(_, State, _) ->
	{ok,State}.
dump(file,J_Array,File) ->
	%%{ok,File} = file:open(io_lib:format("cdr_~B-~B-~B+~B+~B+~B.json",[Year,Month,Day,Hour,Min,Sec]),[write]),
	file:write(File,J_Array).
	%%file:close(File);
dump(data_table_json,{Counter,J_Array}) ->
	io_lib:format("{\"aaData\":~s}",[J_Array ++ "]"]);
dump(json,{Counter,J_Array}) ->
	J_Array.
